import time

from machine import I2C, Pin

from ssd1306 import SSD1306_I2C

# 定义OLED
i2c = I2C(0, scl=Pin(5), sda=Pin(4))
oLed = SSD1306_I2C(128, 64, i2c, addr=60)

D4 = Pin(12, Pin.OUT)

# 定义按钮
button = Pin(1, Pin.IN, Pin.PULL_DOWN)


# 菜单
def display_menu(index):
    oLed.fill(0)
    oLed.text("Menu", 0, 0)
    oLed.text("-" * 20, 0, 10)
    for i in range(len(menus)):
        if index == i:
            oLed.text("> " + menus[i], 0, 20 + i * 10)
        else:
            oLed.text(menus[i], 0, 20 + i * 10)
    oLed.show()


# 按钮回调函数
def interrupt_handler(btn):
    global btn_index, menus
    time.sleep_ms(10)

    if btn.value() == 0:
        D4.on()
        print(btn.value(), btn_index)
        btn_index = (btn_index + 1) % len(menus)
        display_menu(btn_index)
    else:
        D4.off()


# 定义中断
button.irq(trigger=Pin.IRQ_RISING, handler=interrupt_handler)

if __name__ == '__main__':
    menus = ["Item 1", "Item 2", "Item 3", "Item 4"]
    btn_index = 0
    display_menu(btn_index)
    D4.off()
